package ink.lovejinhu.swardToOffer;

import ink.lovejinhu.common.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @author jinhu
 * created 2021-08-12 9:26
 */
public class Offer_032_II {
    /**
     * 层序遍历
     *
     * @param root
     * @return
     */
    public List<List<Integer>> levelOrder(TreeNode root) {
        if (root == null) {
            List<List<Integer>> outer = new ArrayList<>();

            return outer;
        }
        List<List<Integer>> res = new ArrayList<>(); //存结果
        LinkedList<TreeNode> treeNodes = new LinkedList<>();  //队列
        treeNodes.add(root);
        while (!treeNodes.isEmpty()) {
            ArrayList<Integer> temp = new ArrayList<>();
            int size = treeNodes.size();
            for (int i = 0; i < size; i++) {
                TreeNode poll = treeNodes.poll();
                temp.add(poll.val);
                if (poll.left != null) {
                    treeNodes.add(poll.left);
                }
                if (poll.right != null) {
                    treeNodes.add(poll.right);
                }
            }
            res.add(temp);
        }
        return res;
    }

    public static void main(String[] args) {
        /**
         * 1
         2   5
         3
         4
         */


        TreeNode node1 = new TreeNode(1);
        TreeNode node2 = new TreeNode(2);
        TreeNode node3 = new TreeNode(3);
        TreeNode node4 = new TreeNode(4);
        TreeNode node5 = new TreeNode(5);
        node1.left = node2;
        node2.right = node3;
        node3.left = node4;
        node1.right = node5;
        List<List<Integer>> lists = new Offer_032_II().levelOrder(node1);
        System.out.println(lists);
    }

}
